using System;
using System.Collections.ObjectModel;
using System.Reflection.Emit;
using Pine.Core;
using Pine.SourceParser.Tree;

namespace Pine.CodeGen
{
	public static class ContinueStatementCodeGenerator
	{
		public static void GenerateBytecode(Context ctx, Statement stmt) {
			ContinueStatement continuestmt = (ContinueStatement) stmt;
			
			if (ctx.loopNames.Count == 0)
				throw new Exception("Attempting to continue, but there is nothing to continue to");
			
			if (continuestmt.Name == null) {
				ctx.il.Emit(OpCodes.Br, ctx.continueLabels.Peek());
			}
			else {
				string[] loopNames = ctx.loopNames.ToArray();
				int index = Array.IndexOf<string>(loopNames, continuestmt.Name);
				
				if (index == -1)
					throw new Exception("Attempting to perform a named continue, but the name doesn't match anything that can be continued.");
				
				ctx.il.Emit(OpCodes.Br, ctx.continueLabels.ToArray()[index]);
			}
		}
	}
}

